package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.dao.OrganizationRepository;
import com.cpit.platform.dto.Organization;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.platform.dto.OperLog;
import com.cpit.qualitycontrol.common.constant.LogConstantEx;
import com.cpit.qualitycontrol.entity.SubTask;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.service.SubTaskService;
import com.cpit.qualitycontrol.vo.SubTaskCheckVo;
import com.cpit.qualitycontrol.vo.SubTaskSubmitCoordinateVo;
import com.cpit.qualitycontrol.vo.SubTaskSubmitVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xxx on 2017/10/11.
 */
@Controller
@RequestMapping(value = "/subtask")
public class SubTaskController {

    private final String loggerName = this.getClass().getName();

    @Autowired
    SubTaskService subTaskService;

    @Autowired
    OrganizationRepository organizationRepository;

    @Autowired
    OperLogService operLogService;

    @ApiOperation(value = "查询待处理任务", notes = "通过条件查询待处理任务，返回List方式" +
            "支持模糊查询。")
    @ResponseBody
    @GetMapping("/queryTodoSubTask")
    public List<SubTask> queryTodoSubTask(
            @ApiParam(value = "当前页数， 以1开始。")
            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "当前页的内容长度。")
            @RequestParam(value = "size", required = false, defaultValue = "20") int size,
            @ApiParam(value = "排序方式：asc为升序，desc为降序。")
            @RequestParam(value = "order", required = false, defaultValue = "desc") String order,
            @ApiParam(value = "排序字段，与dto中声明的字段名称一致。")
            @RequestParam(value = "orderBy", required = false, defaultValue = "updateTaskTime") String orderBy,
            @ApiParam(value = "产品线ID")
            @RequestParam(value = "productLineId", required = false) Long productLineId,
            @ApiParam(value = "项目名称，模糊搜索")
            @RequestParam(value = "projectName", required = false, defaultValue = "") String projectName,
            @ApiParam(value = "施工单位名称，模糊搜索")
            @RequestParam(value = "constructionTeamName", required = false, defaultValue = "") String constructionTeamName,
            @ApiParam(value = "设备编号，模糊搜索")
            @RequestParam(value = "deviceName", required = false, defaultValue = "") String deviceName,
            @ApiParam(value = "设备类型ID")
            @RequestParam(value = "deviceTypeId", required = false) Long deviceTypeId,
            @ApiParam(value = "工单类型ID")
            @RequestParam(value = "workOrderTypeId", required = false) Long workOrderTypeId,
            @ApiParam(value = "任务状态")
            @RequestParam(value = "subTaskState", required = false) Integer subTaskState,
            @ApiParam(value = "设备地址") @RequestParam(value = "addr", required = false) String addr,
            @ApiParam(value = "是否为查询历史任务，true=查询历史任务 false=查询待办任务")
            @RequestParam(value = "isHistory", required = false, defaultValue = "false") Boolean isHistory) {

        LogOperator.debug(loggerName, "page = [" + page + "], size = [" + size + "], order = [" + order +
                "], orderBy = [" + orderBy + "], productLineId = [" + productLineId + "], projectName = [" +
                projectName + "], constructionTeamName = [" + constructionTeamName + "], deviceName = [" + deviceName +
                "], deviceTypeId = [" + deviceTypeId + "], workOrderTypeId = [" + workOrderTypeId +
                "], subTaskState = [" + subTaskState + "]");
        return subTaskService.queryTodoSubTaskByUserId(getLoginUser().getUser().getId(), page, size, order, orderBy,
                productLineId, projectName, constructionTeamName, deviceName, deviceTypeId, workOrderTypeId,
                subTaskState, isHistory, addr);
    }


    @SuppressWarnings("rawtypes")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。" +
                    "构造查询条件queryCond Map对象时，有选择条件的的参数key分别为productLineId, projectName, " +
                    "constructionTeamName, deviceName, deviceTypeId, workOrderTypeId, subTaskState",
                    required = true, dataType = "TableDataQueryCondition")
    })
    @ResponseBody
    @RequestMapping(value = "/queryTodoSubTaskJqg", method = RequestMethod.GET)
    public TableJsonData queryTodoSubTaskJqg(TableDataQueryCondition cond) {

        LogOperator.debug(loggerName, "cond = [" + cond + "]");
        return subTaskService.findByConditionJqg(getLoginUser().getUser().getId(), cond, false);
    }


    @ApiOperation(value = "合格率统计", notes = "通过条件查询合格率，返回List方式" +
            "支持模糊查询。")
    @ResponseBody
    @GetMapping("/queryQualifiedRate")
    public List<SubTask> qualifiedRate(
            @ApiParam(value = "当前页数， 以1开始。")
            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "当前页的内容长度。")
            @RequestParam(value = "size", required = false, defaultValue = "20") int size,
            @ApiParam(value = "排序方式：asc为升序，desc为降序。")
            @RequestParam(value = "order", required = false, defaultValue = "desc") String order,
            @ApiParam(value = "排序字段，与dto中声明的字段名称一致。")
            @RequestParam(value = "orderBy", required = false, defaultValue = "endTaskTime") String orderBy,
            @ApiParam(value = "产品线ID")
            @RequestParam(value = "productLineId", required = false) Long productLineId,
            @ApiParam(value = "项目名称，模糊搜索")
            @RequestParam(value = "projectName", required = false, defaultValue = "") String projectName,
            @ApiParam(value = "施工单位名称，模糊搜索")
            @RequestParam(value = "constructionTeamName", required = false, defaultValue = "") String constructionTeamName,
            @ApiParam(value = "审核开始时间")
            @RequestParam(value = "beginTime", required = false, defaultValue = "") String beginTime,
            @ApiParam(value = "审核结束时间")
            @RequestParam(value = "endTime", required = false, defaultValue = "") String endtime,
            @ApiParam(value = "审核次数")
            @RequestParam(value = "auditCount", required = false, defaultValue = "1") Integer auditCount) {

        LogOperator.debug(loggerName, "page = [" + page + "], size = [" + size + "], order = [" + order +
                "], orderBy = [" + orderBy + "], productLineId = [" + productLineId + "], projectName = [" + projectName +
                "], constructionTeamName = [" + constructionTeamName + "], beginTime = [" + beginTime +
                "], endtime = [" + endtime + "], auditCount = [" + auditCount + "]");


        return null;
    }


    @SuppressWarnings("rawtypes")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。" +
                    "构造查询条件queryCond Map对象时，有选择条件的的参数key分别为productLineId, projectName, " +
                    "constructionTeamName, deviceName, deviceTypeId, workOrderTypeId, subTaskState",
                    required = true, dataType = "TableDataQueryCondition")
    })
    @ResponseBody
    @RequestMapping(value = "/queryHistoryTodoSubTaskJqg", method = RequestMethod.GET)
    public TableJsonData queryHistoryTodoSubTaskJqg(TableDataQueryCondition cond) {

        LogOperator.debug(loggerName, "cond = [" + cond + "]");
        return subTaskService.findByConditionJqg(getLoginUser().getUser().getId(), cond, true);
    }


    @ApiOperation(value = "查询单个任务", notes = "参数为子任务ID")
    @ResponseBody
    @GetMapping(value = "/{subTaskId}")
    public Result getSubTask(@ApiParam(value = "子任务ID", required = true)
                             @PathVariable("subTaskId") Long subTaskId) {
        try {

            LogOperator.debug(loggerName, "subTaskId = [" + subTaskId + "]");
            SubTask subTask = subTaskService.querySubTaskById(subTaskId);
            Map<String, String> orgMap = getOrgMap();
            subTask.setOrganizationTeamName(orgMap.get(String.valueOf(subTask.getOrganizationTeamId())));
            return new Result<>(Result.CODE_SUCCESS, "", subTask);
        } catch (Exception e) {
            LogOperator.err(loggerName, "getSubTask error", e);
            return new Result<>(Result.CODE_FAILED, e.getMessage(), subTaskId);
        }
    }


    /**
     * 获取组织机构与ID 与名称对应的Map
     *
     * @return
     */
    private Map<String, String> getOrgMap() {
        List<Organization> organizationList = organizationRepository.findAll();
        Map<String, String> orgIdNameMap = new HashMap();
        Map<String, Organization> orgIdOrgMap = new HashMap();
        for (Organization organization : organizationList) {
            orgIdOrgMap.put(String.valueOf(organization.getId()), organization);
        }
        for (Organization organization : organizationList) {
            String name = organization.getName();
            Integer pId = organization.getParentId();
            while (pId != -1) {
                Organization orgParent = orgIdOrgMap.get(String.valueOf(pId));
                name = orgParent.getName() + "/" + name;
                pId = orgParent.getParentId();
            }
            orgIdNameMap.put(String.valueOf(organization.getId()), name);
        }

        LogOperator.debug(loggerName, "map keys:" + orgIdOrgMap.entrySet());

        return orgIdNameMap;
    }

    @ApiOperation(value = "施工任务提交", notes = "施工任务提交，1.子任务ID；2.登录界面输入的用户姓名，可为空；" +
            "3.业务数据，对象；4.提交的图片对象List<SubTaskImageVo>，多个；5.备注；note: 初次提交 SubTaskImageVo 对象的" +
            "subImageId 属性为空，qualified 属性为false；后续提交 SubTaskImageVo 对象的 subImageId 属性不为空，qualified 属性" +
            "已通过的为 true, 不通过的为 false; 可以只提交不通过的图片。")
    @ApiImplicitParam(name = "subTaskSubmitVo", value = "任务提交VO", required = true, dataType = "SubTaskSubmitVo")
    @ResponseBody
    @PostMapping("/submit")
    public Result subTaskSubmit(@RequestBody SubTaskSubmitVo subTaskSubmitVo) {
        OperLog operLog = new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setOperateUser(getLoginUser().getUser().getUsername());
        operLog.setCommand(LogConstant.OPER_MODIFY);
        operLog.setModule(LogConstantEx.MODULE_ASSIGNMENT);

        try {
            LogOperator.debug(loggerName, "subTaskSubmitVo = [" + subTaskSubmitVo + "]");
            subTaskService.subTaskSubmit(getLoginUser().getUser().getId(), subTaskSubmitVo, operLog);
            operLog.setResult(Result.CODE_SUCCESS);
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_SUCCESS, "", null);
        } catch (Exception e) {
            LogOperator.err(loggerName, "subTaskSubmit error", e);
            operLog.setResult(Result.CODE_FAILED);
            operLog.setDetail(operLog.getDetail() + "。失败原因：" + e.getMessage());
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_FAILED, e.getMessage(), subTaskSubmitVo);
        }
    }

    @ApiOperation(value = "提交经纬度信息", notes = "提交经纬度信息，1.子任务ID；2.subTaskBusinessDataId；" +
            "3.经度longitude；4.纬度Latitude")
    @ApiImplicitParam(name = "subTaskSubmitCoordinateVo", value = "提交经纬度VO", required = true, dataType = "SubTaskSubmitCoordinateVo")
    @ResponseBody
    @PostMapping("/subTaskSubmitCoordinate")
    public Result subTaskSubmitCoordinate(@RequestBody SubTaskSubmitCoordinateVo subTaskSubmitCoordinateVo) {
        OperLog operLog = new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setOperateUser(getLoginUser().getUser().getUsername());
        operLog.setCommand(LogConstant.OPER_MODIFY);
        operLog.setModule(LogConstantEx.MODULE_ASSIGNMENT);
        operLog.setDetail("提交经纬度信息");
        try {
            LogOperator.debug(loggerName, "subTaskSubmitCoordinateVo = [" + subTaskSubmitCoordinateVo + "]");
            subTaskService.subTaskSubmitCoordinate(subTaskSubmitCoordinateVo);
            operLog.setResult(Result.CODE_SUCCESS);
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_SUCCESS, "", null);
        } catch (Exception e) {
            LogOperator.err(loggerName, "subTaskSubmitCoordinate error", e);
            operLog.setResult(Result.CODE_FAILED);
            operLog.setDetail(operLog.getDetail() + "。失败原因：" + e.getMessage());
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_FAILED, e.getMessage(), subTaskSubmitCoordinateVo);
        }
    }


    @ApiOperation(value = "施工任务检查", notes = "施工任务检查，1.子任务ID；2.是否合格；3.驳回图片ID；4.备注")
    @ApiImplicitParam(name = "subTaskCheckVo", value = "任务checkVO", required = true, dataType = "SubTaskCheckVo")
    @ResponseBody
    @PostMapping("/check")
    public Result checkTask(@RequestBody SubTaskCheckVo subTaskCheckVo) {
        OperLog operLog = new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setOperateUser(getLoginUser().getUser().getUsername());
        operLog.setCommand(LogConstant.OPER_MODIFY);
        operLog.setModule(LogConstantEx.MODULE_ASSIGNMENT);
        try {

            LogOperator.debug(loggerName, "subTaskCheckVo = [" + subTaskCheckVo + "]");
            subTaskService.subTaskCheck(getLoginUser().getUser().getId(), subTaskCheckVo, operLog);
            operLog.setResult(Result.CODE_SUCCESS);
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_SUCCESS, "", null);
        } catch (Exception e) {
            LogOperator.err(loggerName, "checkTask error", e);
            operLog.setResult(Result.CODE_FAILED);
            operLog.setDetail(operLog.getDetail() + "。失败原因：" + e.getMessage());
            operLogService.writeLog(operLog);
            return new Result<>(Result.CODE_FAILED, e.getMessage(), subTaskCheckVo);
        }
    }


    /**
     * 获取登录用户信息
     *
     * @return
     */
    private UserInfo getLoginUser() {
        UserInfo userDetails = (UserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return userDetails;
    }


}
